package com.weixing.mall.provider.controller.admin;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.weixing.mall.base.constant.GlobalConstant;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import com.weixing.mall.core.annotation.NoNeedAccess;
import com.weixing.mall.core.annotation.NoRepeatSubmit;
import com.weixing.mall.core.annotation.SysLog;
import com.weixing.mall.core.enums.OperateEnum;
import com.weixing.mall.core.enums.OrderAppTagEnum;
import com.weixing.mall.core.enums.OrderSysTagEnum;
import com.weixing.mall.core.support.BaseController;
import com.weixing.mall.core.support.auth.AuthUtil;
import com.weixing.mall.core.support.auth.SysAuth;
import com.weixing.mall.core.support.auth.SysInfo;
import com.weixing.mall.provider.api.model.vo.dto.DepotRPcVo;
import com.weixing.mall.provider.api.service.DepotServiceRpc;
import com.weixing.mall.provider.model.domain.Order;
import com.weixing.mall.provider.model.domain.OrderBinding;
import com.weixing.mall.provider.model.domain.OrderGoods;
import com.weixing.mall.provider.model.dto.*;
import com.weixing.mall.provider.model.query.*;
import com.weixing.mall.provider.model.vo.*;
import com.weixing.mall.provider.service.IOrderBindingService;
import com.weixing.mall.provider.service.IOrderGoodsService;
import com.weixing.mall.provider.service.IOrderPCService;
import com.weixing.mall.provider.service.IOrderService;
import com.weixing.mall.provider.support.excel.GoodsIdentificationExcalDownLoad;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单相关接口
 *
 * @author  gjq
 * @date  2019/10/15
 * @since  1.0
 **/
@RestController
@RequestMapping("order")
public class OrderController extends BaseController {

    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOrderGoodsService orderGoodsService;
    @Autowired
    private IOrderPCService orderPCService;

    @Autowired
    private IOrderBindingService orderBindingService;

    @Autowired
    private DepotServiceRpc depotServiceRpc;

    /**
     * 查看订单详情
     *
     * @param id    订单id
     * @return  订单详情
     */
    @GetMapping("/getOrderDetails/{id}")
    public Result<OrderDetilVo> getOrderDetails(@PathVariable long id) {
        OrderDetilVo orderDetilVo = orderService.selectOrderDetails(id);
        return ResultUtil.success(orderDetilVo);
    }


    /**
     * 首页订单整体情况详情接口
     * @return 整体情况
     */
    @GetMapping("/loadAdminIndex")
    @NoNeedAccess
    public Result loadAdminIndex() {
        Map<String,Object> result=orderPCService.loadAdminIndex();
        return ResultUtil.success(result);
    }

    /**
     * 根据id查找PC订单详情发展时间
     * @param id 订单id
     * @return 发展时间
     */
    @GetMapping("/getOrderDetailsTime/{id}")
    public Result<OrderDetilTimeVo> getOrderDetailsTime(@PathVariable long id) {
        OrderDetilTimeVo orderDetilTimeVo = orderService.selectOrderDetailsTime(id);
        return ResultUtil.success(orderDetilTimeVo);
    }

    /**
     * 改变订单状态
     *
     * @param dto 参数
     * @return 结果
     */
    @PostMapping("changeOrderStatus")
    public Result changeOrderStatus(@Validated ChgOrderStatusDto dto) {
        orderService.changeOrderStatus(dto);
        return ResultUtil.success();
    }

    @ApiOperation(value = "改变app端用户订单状态")
    @PostMapping("changeFrontOrderStatus")
    public Result changeFrontOrderStatus(@Validated ChgFrontOrderStatusDto chgFrontOrderStatusDto) {
        orderService.changeFrontOrderStatus(chgFrontOrderStatusDto);
        return ResultUtil.success();
    }

    @ApiOperation(value = "改变订单支付状态")
    @PostMapping("changeOrderPayStatus")
    public Result changeOrderPayStatus(@Validated ChgOrderPayStatusDto chgOrderPayStatusDto) {
        orderService.changeOrderPayStatus(chgOrderPayStatusDto);
        return ResultUtil.success();
    }


    @ApiOperation(value = "PC端整体订单查询")
    @GetMapping("selectListPC")
    public Result selectListPC(OrderPCQuery orderPCQuery) {
        return ResultUtil.success(orderPCService.selectListPC(orderPCQuery, initMpPage()));
    }


    @ApiOperation(value = "推送商品码，根据查询条件进行商品码的进行推送")
    @GetMapping("selectListPrint")
    public Result selectListPrint(OrderPCQuery orderPCQuery, @SysInfo SysAuth auth) {
        try {
            orderPCService.selectListPrint(orderPCQuery, auth);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(e.getMessage());
        }
        return ResultUtil.success();

    }

    @ApiOperation(value = "更新订单推送商品码状态")
    @PostMapping("updatePrintVal/{ids}")
    public Result updateGoodsSnPrintVal(@PathVariable(value = "ids") Long[] ids) {
        if (ids == null) {
            return ResultUtil.error("无可操作数据！");
        }
        orderPCService.batchUpdateGoodsSnPrintVal(ids);
        return ResultUtil.success();

    }

    @ApiOperation(value = "更新订单推送商品码状态")
    @PostMapping("updatePrintVal")
    public Result updateGoodsSnPrintVal2(OrderIdsDto ids) {
        if (ids == null || ids.getIds() == null) {
            return ResultUtil.error("无可操作数据！");
        }
        orderPCService.batchUpdateGoodsSnPrintVal(ids.getIds());
        return ResultUtil.success();

    }

    @ApiOperation(value = "推送订单码")
    @GetMapping("PushOrderSn/{id}")
    public Result PushOrderSn(@PathVariable String id) {
        String[] tt = id.split(",");
        orderService.PushOrderSn(tt);
        return ResultUtil.success();
    }

    @ApiOperation(value = "订单绑定")
    @PostMapping("orderBilling")
    @NoRepeatSubmit
    public Result orderUntying(@RequestBody OrderBinding orderBinding) {
        if (orderBinding.getCommodityCode() == null || orderBinding.getOrderId() == null) {
            return ResultUtil.error("订单码不可用");
        }
        OrderBinding binding = orderBindingService.getOne(new QueryWrapper<OrderBinding>().eq("commodity_code", orderBinding.getCommodityCode()));
        if (binding != null) {
            if (orderBinding.getOrderId().equals(binding.getOrderId())) {
                return ResultUtil.success();
            }
            return ResultUtil.error("订单码已经绑定");
        }
        OrderBinding order = orderBindingService.getOne(new QueryWrapper<OrderBinding>().eq("order_id", orderBinding.getOrderId()));
        if (order != null) {
            return ResultUtil.error("订单已经绑定");
        }
        orderBindingService.save(orderBinding);
        List<OrderGoods> orderGoodList = orderGoodsService.list(new QueryWrapper<OrderGoods>().eq("order_id", orderBinding.getOrderId()));
        for (OrderGoods orderGoods : orderGoodList) {
            orderGoods.setCommodityCode(orderBinding.getCommodityCode());
            orderGoodsService.updateById(orderGoods);
        }
        return ResultUtil.success();
    }

    /**
     * 订单解绑
     * @param orderId
     * @return
     */
    @ApiOperation(value = "")
    @PostMapping("orderUnbind/{orderId}")
    public Result orderUntying(@PathVariable Long orderId) {
        SysAuth auth = AuthUtil.getSysExt();
        orderBindingService.handlerUnbind(orderId, auth.getUid());
        return ResultUtil.success();
    }

    @ApiOperation(value = "查询解绑列表")
    @GetMapping("selectUntyingList")
    public Result selectUntyingList(OrderUntyingQuery orderUntyingQuery) {
        return ResultUtil.success(orderService.selectUntyingList(orderUntyingQuery, initMpPage()));
    }

    @ApiOperation(value = "查询订单分配列表")
    @GetMapping("selectDistributionShipperList")
    public Result selectDistributionShipperList(OrderPCQuery orderPCQuery) {
        return ResultUtil.success(orderService.selectDistributionShipperList(orderPCQuery, initMpPage()));
    }

    /**
     * 查询已发货订单分配列表
     *
     * @param orderPCQuery  查询参数
     * @return  订单列表
     */
    @GetMapping("selectDeliverOrderList")
    public Result<IPage<OrderListPCVo>> selectDeliverOrderList(OrderPCQuery orderPCQuery) {
        return ResultUtil.success(orderService.selectDeliverOrderList(orderPCQuery, initMpPage()));
    }

    /**
     * 查询已发货订单统计
     *
     * @param orderPCQuery  查询参数
     * @return  统计
     */
    @GetMapping("deliverOrderTotal")
    public Result<StaticVo> deliverOrderTotal(OrderPCQuery orderPCQuery) {
        return ResultUtil.success(orderService.deliverOrderTotal(orderPCQuery));
    }

    @ApiOperation(value = "查询已发货订单分配列表-导出")
    @GetMapping("selectDeliverOrderListExcal")
    @SysLog(type = OperateEnum.E,desp = "已发货订单分配列导出")
    public Result selectDeliverOrderListExcal(OrderPCQuery orderPCQuery) {
        return ResultUtil.success(orderService.selectDeliverOrderList(orderPCQuery, new Page(1, -1)));
    }

    @ApiOperation(value = "分配发货员")
    @PostMapping("DistributionShipper")
    public Result distributionShipper(@RequestBody List<DistributionShipperDto> distributionShipperDtoList) {
        orderService.distributionShipper(distributionShipperDtoList);
        return ResultUtil.success();
    }

    @ApiOperation(value = "发货部订单修改")
    @PostMapping("shipperChgOrder")
    public Result shipperChgOrder(@SysInfo SysAuth auth, @Validated ShipperChgInfoDto shipperChgInfoDto) {
        //orderService.shipperChgOrder(shipperChgInfoDto, auth.getUid());
        FrontShipperUpdateGoodsStatusDto fsugsd = new FrontShipperUpdateGoodsStatusDto();
        fsugsd.setOrderId(shipperChgInfoDto.getId());
        fsugsd.setProductStatus(shipperChgInfoDto.getProductStatus());
        fsugsd.setWaitDay(shipperChgInfoDto.getWaitDay());
        fsugsd.setExpressSn(shipperChgInfoDto.getExpressSn());
        if (shipperChgInfoDto.getOuterPrice() != null) {
            fsugsd.setOuterPrice(new BigDecimal(shipperChgInfoDto.getOuterPrice()));
        }
        orderService.updateGoodsStatus(fsugsd);
        return ResultUtil.success();
    }

    @ApiOperation(value = "发货部订单仓库修改")
    @PostMapping("shipperChgDepot")
    public Result shipperChgDepot(@SysInfo SysAuth auth, @Validated ShipperChgInfoDto shipperChgInfoDto) {
        orderService.shipperChgDepot(shipperChgInfoDto, auth.getUid());
        return ResultUtil.success();
    }

    @ApiOperation(value = "检货管理/货物标识管理")
    @PostMapping("goodsIdentification")
    @NoNeedAccess
    public Result goodsIdentification(GoodsIdentificationQuery goodsIdentificationQuery) {
        return ResultUtil.success(orderService.goodsIdentification(goodsIdentificationQuery, initMpPage()));
    }

    @ApiOperation(value = "检货管理/货物标识管理:Excal下载")
    @PostMapping("goodsIdentificationExcal")
    public void goodsIdentificationExcal(GoodsIdentificationQuery goodsIdentificationQuery, String filedNames, HttpServletResponse response) {
        List<GoodsIdentificationVo> list = orderService.goodsIdentification(goodsIdentificationQuery);
        GoodsIdentificationExcalDownLoad.ExcalDownload(list, filedNames, response);
    }

    @ApiOperation(value = "根据商品Id和商品的sku查询出货品的Id")
    @GetMapping("selectProductId")
    public Result selectProductId(ProductIdQuery productIdQuery) {
        return ResultUtil.success(orderService.selectProductId(productIdQuery));
    }

    /**
     * 新增查询规则：查询条件  属于外采仓的已封单的订单
     * 外采仓条件代码内查询定死-.-!(I don't want to)
     *
     * @param orderQuery
     * @return
     */
    @ApiOperation(value = "历史订单查询")
    @GetMapping("historyOrder")
    public Result historyOrder(OrderPCQuery orderQuery) {
        Result<DepotRPcVo> outVo = depotServiceRpc.getBycode(GlobalConstant.DepotCode.OUT);
        if (outVo.isSuccess() && ObjectUtil.isNotEmpty(outVo.getData())) {
            orderQuery.setDepotId(outVo.getData().getId());
        }
        return ResultUtil.success(orderService.historyOrder(initMpPage(), orderQuery));
    }

    @ApiOperation(value = "已封单或待封单订单查询-（排除外采仓）")
    @GetMapping("sealedBillOrder")
    public Result sealedBillOrder(OrderPCQuery orderQuery) {
        return ResultUtil.success(orderService.historyOrder(initMpPage(), orderQuery));
    }

    @ApiOperation(value = "外采已封单或待发货订单查询")
    @GetMapping("sealedBillOrder2")
    public Result sealedBillOrder2(OrderPCQuery orderQuery) {
        return ResultUtil.success(orderService.historyOrder2(initMpPage(), orderQuery));
    }

    @ApiOperation(value = "封单")
    @PostMapping("sealingSheet")
    @NoRepeatSubmit
    public Result sealingSheet(SealingSheetDto sealingSheetDto, @SysInfo SysAuth sysAuth) {
        orderPCService.sealingSheetLevel2(sealingSheetDto, sysAuth);
        return ResultUtil.success();
    }

    @ApiOperation(value = "封单新----整体订单封单")
    @GetMapping("sealingSheet02")
    @NoRepeatSubmit
    public Result sealingSheet(OrderPCQuery orderPCQuery, SealingSheetDto sealingSheetDto, @SysInfo SysAuth sysAuth) {
        List<OrderListPCVo> listPCVos = orderPCService.selectListPC(orderPCQuery);
        if (listPCVos.size() > 1000) {
            return ResultUtil.error("封单数量过多");
        }
        List<Long> ids = listPCVos.stream().map(o -> o.getId()).collect(Collectors.toList());
        sealingSheetDto.setOrderIds(ids.toArray(new Long[ids.size()]));
        orderPCService.sealingSheet(sealingSheetDto, sysAuth);
        return ResultUtil.success();
    }

    @ApiOperation(value = "封单二期----整体订单封单")
    @PostMapping("sealingSheetlevel2")
    @NoRepeatSubmit
    public Result sealingSheetlevel2(OrderPCQuery orderPCQuery, SealingSheetDto sealingSheetDto, @SysInfo SysAuth sysAuth) {
        List<OrderListPCVo> listPCVos = orderPCService.selectListPC(orderPCQuery);
        if (listPCVos.size() > 1000) {
            return ResultUtil.error("封单数量过多");
        }
        if (listPCVos.size() ==0) {
            return ResultUtil.error("无封单数据");
        }
        List<Long> ids = listPCVos.stream().map(o -> o.getId()).collect(Collectors.toList());
        sealingSheetDto.setOrderIds(ids.toArray(new Long[ids.size()]));
        orderPCService.sealingSheetLevel2(sealingSheetDto, sysAuth);
        return ResultUtil.success();
    }

    @ApiOperation(value = "已封单管理列表 --- 变更为生成调拨单管理")
    @GetMapping("sealingSheetOrderList")
    public Result sealingSheetOrderList(SealingSheetOrderQuery sealingSheetOrderQuery) {
        //查询外采仓ID 排除外采仓订单
        Result<DepotRPcVo> outVo = depotServiceRpc.getBycode(GlobalConstant.DepotCode.OUT);
        if (outVo.isSuccess() && ObjectUtil.isNotEmpty(outVo.getData())) {
            sealingSheetOrderQuery.setOutDepotId(outVo.getData().getId());
        }
        return ResultUtil.success(orderService.sealingSheetOrderList(initMpPage(), sealingSheetOrderQuery));
    }

    @ApiOperation(value = "已封单订单修改")
    @PostMapping("updateSealingSheetOrder")
    public Result updateSealingSheetOrder(Long orderId, Long depotId, String depotName) {
        orderService.updateSealingSheetOrder(orderId, depotId, depotName);
        return ResultUtil.success();
    }

    @ApiOperation(value = "生成调拨单")
    @PostMapping("createBillTrands")
    public Result createBillTrands(@SysInfo SysAuth auth, String orderIds, Long depotId, String depotName) {
        String msg=orderService.createBillTrands(orderIds, depotId, depotName, auth.getUid());
        if(ObjectUtil.isNull(msg)){
            return ResultUtil.success();
        }
        return ResultUtil.error(msg);
    }

    @ApiOperation(value = "生成调拨单订单列表查询")
    @GetMapping("byDepotId")
    public Result byDepotId(Long depotId) {
        return ResultUtil.success(orderService.byDepotId(initMpPage(), depotId));
    }

    @ApiOperation(value = "调拨单生成")
    @GetMapping("billTrands/{indepotId}")
    @NoRepeatSubmit
    public Result billTrands(@PathVariable Long indepotId, @SysInfo SysAuth sysAuth) {
        orderPCService.billTrands(sysAuth, indepotId);
        return ResultUtil.success();
    }

    @ApiOperation(value = "订单后台标签")
    @GetMapping("getSysTagList")
    public Result getSysTagList() {
        return ResultUtil.success(OrderSysTagEnum.values());
    }

    @ApiOperation(value = "订单代理商端App标签")
    @GetMapping("getAppTagList")
    public Result getAppTagList() {
        return ResultUtil.success(OrderAppTagEnum.values());
    }


    @ApiOperation(value = "订单解绑(二期)")
    @PostMapping("orderUnbound")
    public Result orderUnbound(@RequestBody List<Long> ids) {
        String checkReult=orderPCService.orderCheckUnbound(ids);
        if(null!=checkReult){
            return  ResultUtil.error(checkReult);
        }
        orderPCService.orderUnbound(ids);
        return ResultUtil.success();
    }
    @ApiOperation(value = "订单状态重置（断货和取消的订单进行重置操作） 二期")
    @GetMapping("resetStatus/{id}")
    public Result resetStatus(@PathVariable Long id) {
        String checkReult=orderPCService.checkOrderStatus(id);
        if(null!=checkReult){
            return  ResultUtil.error(checkReult);
        }
        orderPCService.orderResetStatus(id);
        return ResultUtil.success();
    }


    @ApiOperation(value = "订单绑定(二期)")
    @PostMapping("orderBound")
    @NoNeedAccess
    public Result orderUnbound(@RequestBody OrderBoundDto orderBoundDto) {
        List<Long> ids= Lists.newArrayList();
        ids.add(orderBoundDto.getOrderId());
        String checkReult=orderPCService.orderCheckUnbound(ids);
        if(null!=checkReult){
            if(!checkReult.contains("未绑定订单")){
                return  ResultUtil.error(checkReult);
            }

        }
        if("null".equals(orderBoundDto.getDepotSn())||ObjectUtil.isEmpty(orderBoundDto.getDepotSn())||ObjectUtil.isNull(orderBoundDto.getDepotSn())){
            return  ResultUtil.error("该绑定的库存编码为空，不允许绑定！");
        }
       int result= orderPCService.OrderBoundDto(orderBoundDto);
        if(result==1){
            return ResultUtil.error("库存编码存在未解绑，不允许重新绑定");
        }
        return ResultUtil.success();
    }

    /**
     * 订单图片同步接口
     * @return
     */
    @ApiOperation(value = "订单图片同步接口")
    @GetMapping("orderSyn")
    @NoNeedAccess
    public Result orderSyn() {
        orderPCService.orderSyn();
        return ResultUtil.success();
    }
}
